/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author karenAndy
 */
public class Tree23<T> implements InterfaceTree<T> {

    Node<T> root;

    public Tree23() {
        root = new Node("");
    }

    public void ReorganizeTree(Node temp, T element) {

        int other = Integer.parseInt(element.toString());

        int value, temp2;

        temp.CheckTree();
        if (!temp.areElements) {
            if (temp.getElement1().toString().equals("") || temp.getElement1() == null) {
                temp.setElement1(other);
            } else {
                value = Integer.parseInt(temp.getElement1().toString());
                if (other < value && temp.getElement2() == null) {
                    temp2 = value;
                    temp.setElement1(other);
                    temp.setElement2(value);
                } else if (temp.getElement2() == null) {
                    temp.setElement2(other);
                }

            }
        } else if (other < Integer.parseInt(temp.getElement1().toString())) {
            temp.CheckTree();
            if (temp.getLeft() == null) {
                temp.setLeft(new Node(other));
            } else {
                if (!temp.getLeft().areElements) {
                    ReorganizeTree(temp.getLeft(), element);
                }
            }

        } else {
            if (other > Integer.parseInt(temp.getElement1().toString()) && other<Integer.parseInt(temp.getElement2().toString())) {
                temp.CheckTree();
                if (temp.getCenter() == null) {
                    temp.setCenter(new Node(other));
                } else {
                    if (!temp.getCenter().areElements) {
                        ReorganizeTree(temp.getCenter(), element);
                    }
                }
            } else {
                if (other > Integer.parseInt(temp.getElement2().toString())) {
                    temp.CheckTree();
                    if (temp.getRight() == null) {
                        temp.setRight(new Node(other));
                    } else {
                        if (!temp.getRight().areElements) {
                            ReorganizeTree(temp.getRight(), element);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void Add(Object element) {
        ReorganizeTree(root, (T)element);
    }

    @Override
    public Object Remove(Object element) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String Show() {
        return root.toString();
    }
}
